﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.BD
{
    public partial class RoleAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {

                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        public void GetRoleList()
        {
            List<BD_Role> list = DALSession.Current.BD_RoleDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, r => 1 == 1, "Name", true).ToList();
            int count = DALSession.Current.BD_RoleDAL.GetCount(r => 1 == 1);
            Response.Write(JsonHelper.toPageJson(list, count));
        }
        /// <summary>
        /// 添加或编辑角色
        /// </summary>
        public void AddRole()
        {
            string action = Request["action"].ToString();
            if (action == "add")
            {
                BD_Role role = new BD_Role() { AddTime = DateTime.Now.ToString("yyyy-MM-dd") };
                ModelTools.Form2Model(Request.Form, role);
                DALSession.Current.BD_RoleDAL.Add(role);
                DALSession.Current.BD_RoleDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true));
            }
            else if (action == "edit")
            {
                int Id = Commons.String2Int32(Request.Form["Id"]);
                BD_Role perNew = DALSession.Current.BD_RoleDAL.GetListBy(d => d.Id == Id).FirstOrDefault();

                ModelTools.Form2EditModel(Request.Form, perNew);
                perNew.AddTime = DateTime.Now.ToString("yyyy-MM-dd");
                DALSession.Current.BD_RoleDAL.ModifyAllModel(perNew);
                DALSession.Current.BD_RoleDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
            }
        }
        //删除角色
        public void DelRole()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            DALSession.Current.BD_RoleDAL.DelBy(p => p.Id == Id);
            DALSession.Current.BD_RoleDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 获取权限树，如果传的参数是角色，则获取角色权限树，如果传的参数是用户Id，则获取是特权权限树
        /// </summary>
        public void GetPermTree()
        {
            string type = Request.Form["type"];
            int Id = Commons.String2Int32(Request.Form["Id"]);
            List<BD_Permission> allPerm = Permission.GetAllPerm();
            List<BD_btnPermission> allBtnPerm = Permission.GetAllBtnPerm(allPerm);
            List<int> thisPermIdList = null;
            List<int> thisBtnPermIdList = null;
            if (type == "role")
            {
                thisPermIdList = DALSession.Current.BD_RolePermissionDAL.GetListBy(r => r.RId == Id).Select(r => r.PId).ToList();
                thisBtnPermIdList = DALSession.Current.BD_RoleBtnPermissionDAL.GetListBy(r => r.RId == Id).Select(r => r.BId).ToList();
            }
            else if (type == "user")
            {
                thisPermIdList = DALSession.Current.BD_UserVipPermissionDAL.GetListBy(r => r.vipUserId == Id).Select(r => r.vipPermission).ToList();
                thisBtnPermIdList = DALSession.Current.BD_UserVipBtnPermissionDAL.GetListBy(r => r.vipUserId == Id).Select(r => r.vipBtnPermission).ToList();
            }
            List<BD_Permission> node = Permission.GetPerTreeBySubTree(allPerm, thisPermIdList, allBtnPerm, thisBtnPermIdList);
            string nodeStr = JsonHelper.toJson(node).Replace("Checked", "checked");
            Response.Write(nodeStr);
        }



        /// <summary>
        /// 获取角色权限树
        /// </summary>
        public void GetRolePermTree()
        {
            //int roleId = Convert.ToInt32(Request.Form["Id"]);
            //List<BD_Permission> perm = Permission.GetAllPerm();
            //List<BD_Permission> rolePerm = Permission.GetPermByRole(roleId);
            //List<TreeNode> node = Permission.GetPerTreeBySubTree(perm, rolePerm);
            //string nodeStr = JsonHelper.toJson(node);
            //string newNodeStr = nodeStr.Replace("Checked", "checked");
            //Response.Write(JsonHelper.toJson(newNodeStr));
        }
        /// <summary>
        /// 修改角色权限树
        /// </summary>
        public void EditRolePermTree()
        {
            int Id = Convert.ToInt32(Request.Form["Id"]);
            string type = Request.Form["type"];
            string permIds = Request.Form["permIds"].TrimEnd(',');
            string btnPermIds = Request.Form["btnPermIds"].TrimEnd(',');
            List<int> perNodes = new List<int>();
            List<int> btnPerNodes = new List<int>();
            if (type == "role")
            {
                for (int i = 0; i < permIds.Split(',').Length; i++)
                {
                    //权限节点Id
                    perNodes.Add(Commons.String2Int32(permIds.Split(',')[i]));
                }
                for (int i = 0; i < btnPermIds.Split(',').Length; i++)
                {
                    //按钮节点Id
                    btnPerNodes.Add(Commons.String2Int32(btnPermIds.Split(',')[i]));
                }
                DALSession.Current.BD_RolePermissionDAL.DelBy(p => p.RId == Id);
                DALSession.Current.BD_RoleBtnPermissionDAL.DelBy(p => p.RId == Id);
                foreach (var perId in perNodes)
                {
                    DALSession.Current.BD_RolePermissionDAL.Add(new BD_RolePermission() { PId = perId, RId = Id });
                }
                foreach (var btnPerId in btnPerNodes)
                {
                    DALSession.Current.BD_RoleBtnPermissionDAL.Add(new BD_RoleBtnPermission() { BId = btnPerId, RId = Id });
                }

                ////查到由于修改权限，导致该角色没有的待办事宜，如果该角色对应的用户还存在，则需要将其删除
                //var notContainPer = DALSession.Current.View_BD_WaitDealDAL.GetListBy(p => !perNodes.Contains((int)p.PerId)).Select(p => p.Id).ToList();
                ////查询该角色对应的用户
                //var roleToUserIds = DALSession.Current.BD_UserRoleDAL.GetListBy(u => u.RId == Id).Select(u => u.UId).ToList();
                //DALSession.Current.BD_UserWaitDealDAL.DelBy(u => roleToUserIds.Contains(u.uId) && notContainPer.Contains(u.wId));
            }
            else if (type == "user")
            {
                for (int i = 0; i < permIds.Split(',').Length; i++)
                {
                    perNodes.Add(Commons.String2Int32(permIds.Split(',')[i]));
                }
                for (int i = 0; i < btnPermIds.Split(',').Length; i++)
                {
                    btnPerNodes.Add(Commons.String2Int32(btnPermIds.Split(',')[i]));
                }
                DALSession.Current.BD_UserVipPermissionDAL.DelBy(p => p.vipUserId == Id);
                DALSession.Current.BD_UserVipBtnPermissionDAL.DelBy(p => p.vipUserId == Id);
                foreach (var perId in perNodes)
                {
                    DALSession.Current.BD_UserVipPermissionDAL.Add(new BD_UserVipPermission() { vipPermission = perId, vipUserId = Id });
                }
                foreach (var btnPerId in btnPerNodes)
                {
                    DALSession.Current.BD_UserVipBtnPermissionDAL.Add(new BD_UserVipBtnPermission() { vipBtnPermission = btnPerId, vipUserId = Id });
                }

            }
            DALSession.Current.BD_RolePermissionDAL.SaveChanges();

            List<int> changeUserIds = new List<int>();
            if (type == "role")
            {
                changeUserIds = DALSession.Current.BD_UserRoleDAL.GetListBy(u => u.RId == Id).Select(u => u.UId).ToList();
            }
            else if (type == "user")
            {
                changeUserIds.Add(Id);
            }
            // 审批/待办事宜 不做进系统
            //var allWaitDeal = DALSession.Current.View_BD_WaitDealDAL.GetListBy(p => 1 == 1).ToList();
            //foreach (var userId in changeUserIds)
            //{
            //    var thisPermIds = Permission.GetPermByUserId(userId).Select(p => p.Id).ToList();
            //    var notContainsWait = allWaitDeal.Where(w => !thisPermIds.Contains((int)w.PerId)).Select(w => w.Id).ToList();
            //    //DALSession.Current.BD_UserWaitDealDAL.DelBy(w => w.uId == userId && notContainsWait.Contains(w.wId));
            //}
            DALSession.Current.BD_RolePermissionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));

        }
        //获取该角色的权限按钮的树节点
        public void GetRoleBtnPer()
        {
            //获取角色的ID
            int roleId = Convert.ToInt32(Request.Form["Id"]);
            //获取角色的所有权限二级页面
            List<BD_Permission> rolePerm = Permission.GetPermByRoleEr(roleId);
            //获取该角色选中的按钮权限Id集合
            List<int> roleBtnPerm = Permission.GetBtnPermIdListByRole(roleId);
            //获取用户所有权限二级页面下的按钮
            List<BD_btnPermission> allBtnPerm = Permission.GetAllBtnPerm(rolePerm);
            //创建树节点
            List<TreeNode> node = Permission.GetBtnTree(rolePerm, allBtnPerm, roleBtnPerm);
            string nodeStr = JsonHelper.toJson(node).Replace("Checked", "checked");
            Response.Write(nodeStr);
        }
        //更改该角色的权限按钮
        public void EditRoleBtnPermTree()
        {
            //获取角色的ID
            int roleId = Convert.ToInt32(Request.Form["Id"]);
            List<int> nodes = new List<int>();
            string nodesStr = Request.Form["PermIds"].ToString();
            for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
            {
                nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
            }
            DALSession.Current.BD_RoleBtnPermissionDAL.DelBy(p => p.RId == roleId);
            foreach (var PId in nodes)
            {
                DALSession.Current.BD_RoleBtnPermissionDAL.Add(new BD_RoleBtnPermission() { RId = roleId, BId = PId });
            }
            DALSession.Current.BD_RoleBtnPermissionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true));
        }
    }
}